// ignore_for_file: prefer_final_fields, must_be_immutable

/*
 * @Author: CodeHare
 * @Date: 2023-11-20 14:19:16
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-24 17:24:58
 * @Description: 报障单列表
 */
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/app_permission/permission_widget.dart';
import 'package:yt_devops/components/list_empty_widget.dart';
import 'package:yt_devops/components/time_range_picker.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/components/yt_bottom_picker.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_site_tags.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_status_tags.dart';
import 'package:yt_devops/pages/tasks/my_fault_report/fault_report_list_controller.dart';
import 'package:yt_devops/pages/tasks/my_fault_report/fault_report_list_Item.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';

class FaultReportListView extends StatelessWidget {
  FaultReportListView({Key? key}) : super(key: key);

  final controller = Get.put(FaultReportListController());
  final state = Get.find<FaultReportListController>().state;

  DecoratedBox _searchInput(context) {
    return DecoratedBox(
      decoration: const BoxDecoration(color: Colour.white),
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
              height: 54,
              margin: EdgeInsets.only(left: 16.w),
              child: BrnSearchText(
                innerColor: Colour.backgroundColor,
                hintText: state.hintText,
                hintStyle: TextStyle(
                  fontSize: 16.sp,
                  color: Colour.hintTextColor,
                ),
                prefixIcon: Container(
                  margin: EdgeInsets.only(
                    left: 22.w,
                    top: 12,
                    bottom: 12,
                  ),
                  child: Image.asset(
                    ImageAssets.magnifier,
                    width: 16.w,
                    height: 16,
                  ),
                ),
                maxHeight: 54,
                autoFocus: false,
                focusNode: controller.searchSiteFocusNode,
                innerPadding: const EdgeInsets.all(0),
                borderRadius: const BorderRadius.all(
                  Radius.circular(6),
                ),
                outSideColor: Colors.transparent,
                searchController: controller.searchController,
                controller: controller.textController,
                textInputType: TextInputType.text,
                onTextCommit: (content) =>
                    controller.getSearchFaultReportName(content),
                onTextClear: () {
                  controller.getSearchFaultReportName("");
                  return false;
                },
              ),
            ),
          ),
          GestureDetector(
            onTap: () => _toFilter(context),
            child: Padding(
              padding: EdgeInsets.fromLTRB(20.w, 0, 16.w, 0),
              child: Image.asset(
                ImageAssets.iconFilter,
                width: 20.w,
                height: 20,
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _toFilter(BuildContext context) {
    ytBottomPicker(context, mainButtonOnTap: () {
      controller.loadData();
      Get.back();
    }, resetTap: (setstate) {
      setstate(() {
        controller.startTime = "";
        controller.endTime = "";
        controller.state.startTime = "";
        controller.state.endTime = "";
        controller.state.status = null;

        controller.selectedSites.clear();
      });
    }, builder: (context) {
      return StatefulBuilder(
        builder: (context, setState) => Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            /// 创建时间
            TimeRangePicker(
              title: '创建时间',
              padding: EdgeInsets.only(right: 16.w),
              startTime: controller.startTime,
              endTime: controller.endTime,
              onChange: (start, end) {
                controller.startTime = start;
                controller.endTime = end;
                controller.state.startTime =
                    controller.startTime.replaceAll("/", "-");
                controller.state.endTime =
                    controller.endTime.replaceAll("/", "-");
              },
            ),

            /// 站点
            const SizedBox(height: 3),
            FilterSiteTags(
              selectedSites: controller.selectedSites,
              onChange: (sites) {
                controller.selectedSites = sites;
                print("一直是 ${controller.state.siteIds}");
              },
            ),

            /// 任务状态
            const SizedBox(height: 8),
            FilterStatusTags<ReportTaskStatusType>(
              ReportTaskStatusType.values,
              labelName: (status) => status.label,
              tagWidth: 75.w,
              title: ResKey.workOrderStatus.tr,
              selectTags: controller.state.status == null
                  ? []
                  : [
                      $enumDecodeNullable($ReportTaskStatusTypeEnumMap,
                          controller.state.status)!
                    ],
              onSelect: (status) {
                if (status != null) {
                  controller.state.status = status[0].value;
                }
              },
            ),
          ],
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colour.backgroundColor,
      appBar: AppBarWidget.withRightActions(
        ResKey.taskMyReportWorkOrder.tr,
        actions: [
          PermissionWidget(
            permissionStringList: [PermissionConstant.mineFaultReportManageAdd],
            child: IconButton(
              icon: const Icon(Icons.add),
              iconSize: 26.sp,
              onPressed: () => controller.addNewFaultReportTask(),
            ),
          ),
        ],
      ),
      body: GetBuilder<FaultReportListController>(
        builder: (_) {
          final list = controller.state.dataList;

          return SafeArea(
            child: Stack(
              children: <Widget>[
                GestureDetector(
                  onTap: () => FocusScope.of(context)
                      .requestFocus(controller.searchSiteFocusNode),
                  child: SizedBox(
                    height: ScreenUtil().screenHeight -
                        ScreenUtil().statusBarHeight,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        _searchInput(context),
                        state.isNoData
                            ? ListEmptyWidget(topPosition: 165)
                            : Expanded(
                                child: SmartRefresher(
                                  controller: state.refreshController,
                                  header: ListTips.classicHeader,
                                  footer: ListTips.generateClassicFooter,
                                  onRefresh: () => controller.refreshData(),
                                  onLoading: () => controller.loadMoreData(),
                                  enablePullDown: true,
                                  enablePullUp: controller.state.hasMore,
                                  child: ListView.builder(
                                    itemCount: list.length,
                                    itemBuilder: (context, index) =>
                                        FaultReportItemWidget(
                                      list[index],
                                      onItemTaped: (p0, p1) {
                                        FocusScope.of(context)
                                            .requestFocus(FocusNode());
                                        controller.toDetails(
                                            p0.id!, p0.status!);
                                      },
                                    ),
                                  ),
                                ),
                              ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
